package com.sample.tdf.service.impl;

import cn.com.taiji.common.base.BaseTreeServiceImpl;
import com.sample.tdf.domain.Organization;
import com.sample.tdf.domain.OrganizationRepository;
import com.sample.tdf.dto.EmployeeDTO;
import com.sample.tdf.dto.OrganizationDTO;
import com.sample.tdf.service.IEmployeeService;
import com.sample.tdf.service.IOrganizationEmployeeService;
import com.sample.tdf.service.IOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrganizationServiceImpl extends BaseTreeServiceImpl<OrganizationRepository, Organization, OrganizationDTO> implements IOrganizationService {
    @Autowired
    private IOrganizationEmployeeService iOrganizationEmployeeService;
    @Autowired
    private IEmployeeService iEmployeeService;

    @Override
    public List<OrganizationDTO> findAllTree() {
        List<Organization> all = iBaseRepository.findAll();
        List<OrganizationDTO> dtoList = this.domainListToDTOList(all);
        List<OrganizationDTO> dtoTree = this.listToTree(dtoList, null);

        return dtoTree;
    }

    @Override
    public List<OrganizationDTO> findTreeById(String organizationId) {
        //父机构
        OrganizationDTO organization = findById(organizationId);
        //所有子机构
        List<OrganizationDTO> all = findChildrenByParentId(organizationId);

        //机构下的员工
        for (OrganizationDTO dto:all) {
            List<String> employeeIds = iOrganizationEmployeeService.findSecondIdsByFirstId(dto.getId());
            List<EmployeeDTO> employees = iEmployeeService.findByIds(employeeIds);

            dto.setEmployeeList(employees);
        }

        //转为树
        List<OrganizationDTO> dtoTree = this.listToTree(all, organization.getParentId());

        return dtoTree;
    }
}
